package com.dylan.历史.领扣;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Auther: ankang
 * @Date: 2019/2/21 15:58
 * @Description:
 */
public class $0056区间合并 {

    class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            List<Interval> result = new ArrayList<>();
            if (intervals.isEmpty()) {
                return result;
            }
            if (intervals.size() == 1) {
                result.add(intervals.get(0));
                return result;
            }
            Collections.sort(intervals, Comparator.comparing(i -> i.start));
            for (int i = 1; i < intervals.size(); i++) {
                Interval pre = intervals.get(i - 1);
                Interval curr = intervals.get(i);
                if (pre.end >= curr.start) {
                    curr.start = pre.start;
                    if (pre.end > curr.end) {
                        curr.end = pre.end;
                    }
                } else {
                    result.add(pre);
                }
            }
            result.add(intervals.get(intervals.size() - 1));
            return result;
        }
    }
    class Interval {
        int start;
        int end;
        Interval() { start = 0; end = 0; }
        Interval(int s, int e) { start = s; end = e; }
    }
}